import axios from 'axios'
import router from '../router/index'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = process.env.VUE_APP_BASEURL

export function request(url, data, method) {
  return new Promise((resolve, reject) => {
    axios[method](url, {
      params: data
    }, {
      headers: {
      }
    })
      .then(res => {
        thenSuccess(res,resolve,reject)
      })
      .catch(err => {
        ElMessage({
          type:'error',
          showClose:true,
          center:true,
          message:'请稍后重试'
        })
        reject(err.data)
      })
  })
}

export function post(url, data, method) {
  return new Promise((resolve, reject) => {
    axios[method](url,
      data, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then(res => {
        thenSuccess(res,resolve,reject)
      })
      .catch(err => {
        ElMessage({
          type:'error',
          showClose:true,
          center:true,
          message:'请稍后重试'
        })
        reject(err.data)
      })
  })
}


const thenSuccess = (res, resolve, reject) => {
  if (res.return_code === 200) {
    resolve(res.data)
  } else if (res.return_code === 401 || res.return_code === 402) { //401 没有登录  402 token过期
    ElMessage({
      type:'error',
      showClose:true,
      center:true,
      message:'请登录'
    })
    sessionStorage.setItem("WLJToken",null)
    sessionStorage.setItem("WLJTokenName",null)
    router.replace("/login")
    reject(res)
  }else if (res.return_code === 405) {
    ElMessage({
      type:'error',
      showClose:true,
      center:true,
      message:'验证码错误'
    })
  } else if (res.return_code === 406) {
    clearCookie("WLJToken")
    clearCookie("WLJTokenName")
  } else if (res.return_code === 501) {
    ElMessage({
      type:'error',
      showClose:true,
      center:true,
      message:res.msg
    })
  }else {
    if (res.data.msg) {
      ElMessage({
        type:'error',
        showClose:true,
        center:true,
        message:res.data.msg
      })
    } else {
      ElMessage({
        type:'error',
        showClose:true,
        center:true,
        message:'请稍后重试'
      })
    }

    reject(res)
  }
}

//使用axios.post要设置此响应头，否则后台无法获取数据
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data';

// 允许当前axios携带cookie
axios.defaults.withCredentials = true

// 请求拦截
axios.interceptors.request.use(config => {
  if (sessionStorage.getItem('WLJToken')) {
    //config.headers.Authorization = getCookie('Token');//如果要求携带在请求头中
    config.headers[sessionStorage.getItem("WLJTokenName")] = sessionStorage.getItem('WLJToken');
  }
  //每次请求时可添加加载logo
  return config
}, error => {
  console.log("请求失败");
})

// 响应拦截
axios.interceptors.response.use(config => {
  //直接返回数据
  return config.data
}, error => {
  //弹出错误窗口
  console.log("响应失败");
})
